<template>
  <div class="search-container">
    <form class="search-form" action="/">
      <van-search
        v-model="searchText"
        show-action
        shape="round"
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->
    <!-- 搜索历史记录 -->
    <search-history
      @clearhistory="searchHistories = []"
      :search-histories="searchHistories"
      @search="onSearch"
      v-else
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchResult from './components/search-result'
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
// 导入本地存储封装方法
import { setItem, getItem } from '@/utils/stroage'
export default {
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: JSON.parse(getItem('serach-histories')) || []
    }
  },
  watch: {
    searchHistories (val) {
      // 同步到本地存储
      // console.log(val)
      setItem('serach-histories', JSON.stringify(val))
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      // 显示搜索结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
